import React, { useState, useEffect } from 'react';
import { Breadcrumb, Input, List, Modal, ConfigProvider, Spin } from 'antd';
import type { CommonIssueType } from '@/services/commonIssues';
import { findCommonIssue, findIssueById } from '@/services/commonIssues';
import classnames from 'classnames';
import styles from './index.less';
import zhCN from 'antd/lib/locale/zh_CN';

const { Search } = Input;

type IssueDetailType = {
  visible: boolean;
  onCancel: () => void;
  record?: CommonIssueType | undefined;
};

export const IssueDetailModal: React.FC<IssueDetailType> = (props) => {
  const { visible, onCancel, record } = props;
  return (
    <Modal
      title="问题详情"
      visible={visible}
      onCancel={onCancel}
      className={styles.issueModal}
      width={980}
      footer={null}
    >
      <div className={styles.question}>{record?.commonProblem}</div>
      <div className={styles.timeCount}>
        <div className={styles.time}>发布时间：{record?.createTime}</div>
        <div className={styles.count}>浏览次数：{record?.views}</div>
      </div>
      <div className={styles.detail}>{record?.questionReply}</div>
    </Modal>
  );
};

type IssueParam = {
  page: number;
  size: number | undefined;
  commonProblem?: string;
};

const CommonIssues: React.FC = () => {
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<CommonIssueType>();
  const [issueParam, setIssueParam] = useState<IssueParam>({ page: 1, size: 20 });
  const [commonIssueList, setCommonIssueList] = useState<CommonIssueType[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(1);
  const getIssues = (param: IssueParam) => {
    setLoading(true);
    findCommonIssue(param)
      .then((resp) => {
        if (resp.errorCode === 0) {
          setCommonIssueList(resp?.results);
          setTotalCount(resp?.totalCount);
        }
        setLoading(false);
      })
      .catch((error) => {
        console.log('findCommonIssue error==', error);
        setLoading(false);
      });
  };
  useEffect(() => {
    getIssues(issueParam);
  }, []);
  const onIssueSearch = (e: string) => {
    getIssues({ ...issueParam, commonProblem: e, page: 1 });
    setIssueParam({ ...issueParam, commonProblem: e, page: 1 });
    setCurrent(1);
  };
  const showDetail = async (item: CommonIssueType) => {
    setDetailModalVisible(true);
    setSelectedRecord(item);
    try {
      await findIssueById({ id: item.id });
    } catch (error) {
      console.log('findPolicyCommonQuestionById error');
    }
  };
  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.wrapper}>
        <div className={styles.breadcrumb}>
          <Breadcrumb separator="">
            <Breadcrumb.Item>您的位置</Breadcrumb.Item>
            <Breadcrumb.Separator>:</Breadcrumb.Separator>
            <Breadcrumb.Item href="">首页</Breadcrumb.Item>
            <Breadcrumb.Separator />
            <Breadcrumb.Item href="">常见问题</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className={styles.searchWrapper}>
          <h1>问题搜索</h1>
          <div className={styles.searchBtn}>
            <Search
              placeholder="请输入关键词搜索"
              allowClear
              enterButton="搜索"
              size="large"
              onSearch={onIssueSearch}
            />
          </div>
        </div>
        <Spin spinning={loading}>
          <div className={styles.issueListWrapper}>
            <List
              itemLayout="vertical"
              size="large"
              pagination={{
                defaultPageSize: 20,
                locale: zhCN,
                total: totalCount,
                showSizeChanger: true,
                showQuickJumper: true,
                current,
                showTotal: (total) => {
                  return `共${total}条数据`;
                },
                onChange: (page, pageSize) => {
                  getIssues({ ...issueParam, page, size: pageSize });
                  setCurrent(page);
                },
              }}
              dataSource={commonIssueList}
              footer={null}
              renderItem={(item: CommonIssueType, index) => (
                <List.Item key={index} actions={[]} className={styles.issueListItem}>
                  <List.Item.Meta
                    avatar={
                      <div className={classnames(styles.avatar, styles.questionAvatar)}>Q</div>
                    }
                    title={<a>{item.commonProblem}</a>}
                  />
                  <div className={styles.contentWrapper}>
                    <div className={classnames(styles.avatar, styles.contentAvatar)}>A</div>
                    <div className={styles.answer}>
                      {item.questionReply.substring(0, 100)}
                      <a onClick={showDetail.bind('', item)}>查看更多 → </a>
                    </div>
                  </div>
                </List.Item>
              )}
            />
          </div>
        </Spin>
        <IssueDetailModal
          visible={detailModalVisible}
          onCancel={() => setDetailModalVisible(false)}
          record={selectedRecord}
        />
      </div>
    </ConfigProvider>
  );
};

export default CommonIssues;
